package com.ljq.pub2sub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.ljq.consumer.ConsumerListener2;

/**
 * 而在发布/订阅（Pub/Sub）模型中，如果消费者没有订阅主题或没有启动服务，则获得不到消息。
 */
public class ReceiverSub2 {
	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

	public static void main(String[] args) throws InterruptedException {
		ConnectionFactory connectionFactory;// 连接工厂
		Connection connection = null;// 连接
		Session session;// 会话
		Destination destination;// 消息的目的地
		MessageConsumer messageConsumer;// 消息消费者

		// 实例化连接工厂
		connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
		try {
			connection = connectionFactory.createConnection();
			connection.start();// 启动连接
			// 创建session,第一个参数是否有事务
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
			// 创建消息队列,(创建队列作为目的地),名称要对应
			destination = session.createTopic("FirstTopic1");
			// 创建消息消费者
			messageConsumer = session.createConsumer(destination);

			// 使用监听器监听发送过来的消息
			messageConsumer.setMessageListener(new ConsumerListener2());
			// 一直在监听，循环等待
			/*
			 * while(true){ TextMessage textMessage = (TextMessage)
			 * messageConsumer.receive(10000); if(textMessage != null){
			 * System.out.println("收到消息："+textMessage.getText()); }else{ break; } }
			 */
			Thread.currentThread().sleep(1000*60);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
